package socket

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"net/url"
	"runtime/debug"
	"sync"
	"time"
	"toyota-client1/init/global"
	j_log "toyota-client1/init/j-log"
	"toyota-client1/utils/tools"
)

type WSClient struct {
	Conn      *websocket.Conn `json:"-"`
	WriteLock sync.Mutex      `json:"-"`
}

var Client *WSClient

func WSClientRun() {
	defer func() {
		if err := recover(); err != nil {
			j_log.LogError([]interface{}{"WSClientRun panic", err})
			fmt.Println(string(debug.Stack()))
		}
		j_log.LogInfo([]interface{}{"WSClientRun 连接断开,3秒后重连"})
		time.Sleep(3 * time.Second)
		WSClientRun()
	}()
	addr := global.AppConfig.Section("websocket").Key("addr").String()
	u := url.URL{Scheme: "ws", Host: addr, Path: "/push"}
	j_log.LogInfo([]interface{}{fmt.Sprintf("WSClientRun 正在连接 %s", u.String())})
	conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		j_log.LogError([]interface{}{"WSClient 连接失败:", err.Error()})
		return
	}
	defer conn.Close()
	j_log.LogInfo([]interface{}{fmt.Sprintf("WSClientRun 连接成功 %s", addr)})
	Client = &WSClient{Conn: conn}
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			j_log.LogError([]interface{}{"WSClientRun ReadMessage error:", err.Error()})
			return
		}
		jsonContent := string(message)
		_ = tools.WriteStringToLog(jsonContent, "WSClientRun.log", "a")
		j_log.LogInfo([]interface{}{"【recv】", conn.RemoteAddr().String(), jsonContent})
	}
}

type WSResponseMessage struct {
	Code int    `json:"code"` // 0.操作成功 1.操作失败 2.推送变量 3. 推送报警
	Msg  string `json:"msg"`
	Data string `json:"data"`
}

func (client *WSClient) SendMessage(code int, msg string, data string) (err error) {
	if client == nil {
		return
	}
	resp := WSResponseMessage{}
	resp.Code = code
	resp.Msg = msg
	resp.Data = data
	jsonB, err := json.Marshal(&resp)
	if err != nil {
		j_log.LogError([]interface{}{"SendMessage json.Marshal ERROR", err.Error()})
		return
	}
	client.WriteLock.Lock()
	defer client.WriteLock.Unlock()
	err = client.Conn.WriteMessage(1, jsonB)
	if err != nil {
		j_log.LogError([]interface{}{"SendMessage WriteMessage ERROR", err.Error()})
		return
	}
	return
}
